package net.xiduth.utils.item;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author Tyluur <ItsTyluur@Gmail.com>
 * @since 2012-08-01
 */
public class GrandExchangePrices {

	private static final Map<Integer, Integer> MAP = new HashMap<Integer, Integer>();
	private static final Logger logger = Logger.getLogger(GrandExchangePrices.class.getCanonicalName());

	private static final String PACKED_PATH = "./data/items/grand_exchange/packed_prices.ser";
	private static final String UNPACKED_PATH = "./data/items/grand_exchange/tipit_dump.txt";

	public static final void init() {
		if (!(new File(PACKED_PATH)).exists()) {
			logger.info("Loading unpacked grand exchange prices...");
			loadUnpackedPrices();
			logger.info("Loaded packed grand exchange prices...");
		} else {
			logger.info("Loading packed grand exchange prices...");
			loadPackedPrices();
		}
	}

	private static void loadPackedPrices() {
		try {
			RandomAccessFile in = new RandomAccessFile(PACKED_PATH, "r");
			FileChannel channel = in.getChannel();
			ByteBuffer buffer = channel.map(MapMode.READ_ONLY, 0,
					channel.size());
			while(buffer.hasRemaining()) {
				int item = buffer.getShort() & 0xffff;
				int amount = buffer.getInt();
				MAP.put(item, amount);
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void loadUnpackedPrices() {
		try {
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					PACKED_PATH));
			BufferedReader in = new BufferedReader(
					new FileReader(UNPACKED_PATH));
			String line;
			while((line = in.readLine()) != null) {
				String[] data = line.split(" - ");
				if(data == null)
					continue;
				int item = Integer.parseInt(data[0]);
				int amount = Integer.parseInt(data[1]);
				out.writeShort(item);
				out.writeInt(amount);
				MAP.put(item, amount);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Integer getPrice(int item) {	
		Integer price = (Integer) MAP.get(item);
		return price == null ? -1 : price;
	}


}
